package services

import (
	"encoding/base64"
	"fmt"
	"longmen/server/pkg/common/helper/encrypt"
	"longmen/server/pkg/common/helper/http"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	"time"

	"longmen/server/pkg/common/api_models"
)

func (s *Service) GetEplutusOrder(r *api_models.GetEplutusOrderReq, user *models_main.User) (map[string]interface{}, string, error) {
	fName := "GetEplutusOrder"

	item, err := db_main.GetVipPriceParam(map[string]interface{}{"level": r.Level})
	if err != nil {
		return nil, "", fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	if item.Level <= 0 {
		return nil, "信息错误", fmt.Errorf("%s 信息错误", util.Convert(fName))
	}

	configPri := cache.GetConfigPri()
	//配置参数检测
	if configPri.EplutusToken == "" || configPri.EplutusHashkey == "" || configPri.EplutusEnckey == "" || configPri.EplutusEnciv == "" || configPri.EplutusBid == "" {
		return nil, "暂不支持此支付方式", fmt.Errorf("%s 暂不支持此支付方式", util.Convert(fName))
	}

	orderNo := util.CreateOrderNo(user.Id, "")
	order := &models_main.Order{
		Uid:        user.Id,
		VipLevel:   item.Level,
		Type:       1,
		OrderNo:    orderNo,
		Amount:     item.Price,
		Gold:       item.Gold,
		PayChannel: 4,
		CreateTime: time.Now(),
	}

	if err := db_main.InsertOrder(nil, order); err != nil {
		return nil, "", fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}

	apiPath := ""
	postFields := ""
	uts := time.Now().Unix() * 1000
	if r.Type == 2 {
		apiPath = "https://deposit.eplutusoffline.com/api/1.0/receivable/alipay_add/"
		postFields = fmt.Sprintf("uts=%d&bid=%s&req_order=%s&req_amount=%.2f&dispatch_type=alipay_url",
			uts, configPri.EplutusBid, orderNo, item.Price)
	} else {
		apiPath = "https://deposit.eplutusoffline.com/api/1.0/receivable/add/"
		postFields = fmt.Sprintf("uts=%d&bid=%s&req_order=%s&req_amount=%.2f&auto_dispatch=true&dispatch_type=html_url",
			uts, configPri.EplutusBid, orderNo, item.Price)
	}
	signature := encrypt.GenHMAC256([]byte(postFields), []byte(configPri.EplutusHashkey))
	signStr := base64.StdEncoding.EncodeToString(signature)
	headParam := make(map[string]string)
	headParam["Authorization"] = "Token " + configPri.EplutusToken
	headParam["Content-Type"] = "application/x-www-form-urlencoded"
	headParam["X-EOL-Signature"] = signStr
	headParam["cache-control"] = "no-cache"
	resp, err := http.HttpHParaPost(apiPath, headParam, postFields, 5000, 1000)
	if err != nil {
		return nil, "", fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}

	result := make(map[string]interface{})
	err = util.Json2Struct(string(resp), &result)
	if err != nil {
		return nil, "", fmt.Errorf("%s body :%s %s", util.Convert(fName), string(resp), err.Error())
	}
	if r.Type == 1 {
		if _, ok := result["transrequest_url"]; ok {
			return result, "", nil
		}
	} else {
		if _, ok := result["alipay_url"]; ok {
			return result, "", nil
		}
	}
	return nil, "", fmt.Errorf("%s body :%s", util.Convert(fName), string(resp))
}

func (s *Service) GetVipPriceList() ([]*models_main.VipPrice, error) {
	fName := "GetVipPriceList"
	list, err := db_main.GetVipPricesParam(map[string]interface{}{})
	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return list, nil
}
